package com.yingxin.yx.framework.wx;


import com.yingxin.yx.framework.commons.helper.PropertiesHelper;
import com.yingxin.yx.framework.commons.id.IdHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Service
@SuppressWarnings("all")
public class WeixinSupport {

    /*
    @Autowired
    @Qualifier("jacksonRedisTemplate")
    private RedisTemplate redisTemplate;
    */

    @SuppressWarnings("rawtypes")
    @Autowired
    @Qualifier(value = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    /**
     * 获取微信扫码登录二维码
     */
    public String getQRconnectUrl(String redirectUri) throws UnsupportedEncodingException {
        String stateCode = IdHelper.snowflakeId();
        // redisTemplate.opsForValue().set(SmdhUserConstants.CodeRegion.WECHAT_STATE_CODE + ":" + stateCode, stateCode, 300);
        /**
         * 微信开放平台二维码连接
         */
        String oauthUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
        /**
         * 开放平台回调url
         * 注意：test16web.tunnel.qydev.com 域名地址要和在微信端 回调域名配置 地址一直，否则会报回调地址参数错误
         */
        // String callback = "https://sm2.35dinghuo.com/a/wechat/login";
        String redirect_uri = URLEncoder.encode(redirectUri, "utf-8");
        oauthUrl = oauthUrl
                .replace("APPID", PropertiesHelper.getInstance().getProperty("wxappid"))
                .replace("REDIRECT_URI", redirect_uri)
                .replace("SCOPE", "snsapi_login")
                .replace("STATE", stateCode);
        return oauthUrl;
    }

    /**
     * 扫码成功，验证state 根据 code 获取openId
     */
    public WeixinAccessToken getAccessToken(String code, String state) {
        // Object obj = redisTemplate.opsForValue().get(SmdhUserConstants.CodeRegion.WECHAT_STATE_CODE + ":" + state);
        // if (obj == null) {
        //    throw new BusinessException(SmdhUserConstants.Code.WECHAT_SWEEP_CODE_ERROR);
        // }
        WeixinAccessToken accessToken = WeixinHttpHelper.getAccessToken(
                PropertiesHelper.getInstance().getProperty("wxappid"),
                PropertiesHelper.getInstance().getProperty("wxappsecret"),
                code);
        return accessToken;
    }


    public String getUserInfo(String openId, String accessToken) {
        String json = WeixinHttpHelper.getUserInfo(openId, accessToken);
        return json;
    }

}